from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import math


#目标函数
def aimFunction(x, y):
    z = (x**2 + y**2)
    return z
#绘制目标函数函数图像
def drawFunction(z):
    plt.plot(z)
    plt.savefig("a.png")
    plt.show()

#模拟退火
def SA():
    T0 = 100000 #初始化温度
    T = T0 
    Tmin = 10 #最低温度
    x = np.random.uniform(low = -100, high = 100)
    y = np.random.uniform(low = -100, high = 100)
    k = 50 # 迭代次数
    z = 0 #初始化结果
    t = 0 #时间
    Z = []
    while T >= Tmin:
        for i in range(k):
            #计算目标函数
            z = aimFunction(x,y)
            xNew = x + np.random.uniform(low = -0.055, high = 0.055)
            yNew = y + np.random.uniform(low = -0.055, high = 0.055)
            if (-100 <= xNew  and xNew <= 100) and (-100 <= yNew and yNew <= 100):
                zNew = aimFunction(xNew, yNew)
                if zNew < z:
                    x = xNew
                    y = yNew
                else:
                    p = np.exp( -(zNew - z)/T)
                    r = np.random.uniform(low = 0, high = 1)
                    if r < p:#一定概率接受
                        x = xNew
                        y = yNew
                    else:
                        pass
        t += 1
        T = T0/(1+t)
        z = aimFunction(x,y)
        print(x,y,z)
        Z.append(z)
    return Z

if __name__ == "__main__":
    z = SA()
    drawFunction(z)
